<?php

namespace App\Services;

use App\Models\ZPituitaryComplete;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use App\Models\ZZMed\ZUser;
use Illuminate\Support\Facades\Log;

/**
 * 就诊数据变动，修改关联访视数据
 * @package App\Services
 */
class CompleteService {

    public function __construct() {
        
    }

    public function getCompletion($userId, $visitLevel) {
        foreach ([11, 12, 13, 14, 15, 16] as $k) {
            $ka = "template_" . $k;
            $data[$ka] = 0;
        }
        $data['total'] = 0;
        $data['basic'] = 0;
        $data['bscj'] = 0; //病史采集 
        $completion = DBSelect("
          select category_id , template_id,complete_a,complete_s,complete_b from z_pituitary_complete where user_id = $userId and visit_level = $visitLevel
        ");
        $bscjTual = 0;
        $bscjAll = 0;
        foreach ($completion as $item) {
            if ($item['category_id'] == 0 && $item['template_id'] == 00) {
                $data['basic'] = $item["complete_b"];
            } else if ($item['category_id'] == 100 && $item['template_id'] == 0) {
                $data['total'] = $item["complete_b"];
            } else {
                $kad = "template_" . $item['template_id'];
                if (isset($data[$kad])) {
                    $data[$kad] = $item["complete_b"];
                }
                if($item['category_id'] == 1){
                    $bscjTual += $item["complete_s"];
                    $bscjAll += $item["complete_a"];
                }
                
            }
        }
        $data['bscj']  = $bscjAll > 0 ?  round($bscjTual / $bscjAll * 100, 2): 0; 
        
        return $data;
    }

    public function completion($userId = 0, $visitLevel = 1) {
        //基本信息完成度 = 个人信息  
        $baseScore = $this->baseScore($userId, $visitLevel);
        //问卷完成度 = 病史采集
        $answerScore = $this->answerScore($userId, $visitLevel);
        return true;
    }

    public function baseScore($userId, $visitLevel) {
        //  用户 个人信息 完成度  10项
        //  算分项：患者姓名 性别 出生日期 民族 籍贯 身份证 联系手机/病历首页 家庭成员是否疾病 垂体疾病类型  垂体瘤功能状态/其他垂体疾病




        $baseData1 = ZUser::query()->from('z_user as u')
                        ->selectRaw('u.name,u.bday,u.sex ,u.sfzid,u.cell ,e.ethnicity, e.ancestral_home')
                        ->leftJoin('z_user_extend as e', 'e.user_id', '=', 'u.id')->where('u.id', $userId)->get()->toArray();

        if (!$baseData1) {
            //患者找不到 
            return false;
        }

        $baseData2 = convertsArray(DB::select(
                        "select  p.family_like_has,p.has_chuiti  from  z_pituitary_user p   where p.user_id = $userId
         "));
        $baseData = [];
        foreach ($baseData1 as $item) {
            $baseData['name'] = $item['name'];
            $baseData['bday'] = $item['bday'];
            $baseData['sex'] = $item['sex'];
            $baseData['sfzid'] = $item['sfzid'];
            $baseData['cell'] = $item['cell'];
            $baseData['ethnicity'] = $item['ethnicity'];
            $baseData['ancestral_home'] = $item['ancestral_home'];
        }
        $baseData['family_like_has'] = '';
        $baseData['has_chuiti'] = '';
         foreach ($baseData2 as $item) {
            $baseData['family_like_has'] = $item['family_like_has'];
            $baseData['has_chuiti'] = $item['has_chuiti']; 
        }



        $sex = $baseData['sex'];
        $family_like_has = $baseData['family_like_has'];
        $has_chuiti = $baseData['has_chuiti'];
        $baseData = array_filter($baseData);
        $baseScore = count($baseData);

        //生日字段 默认0000-00-00 ， 单独处理
        if ($baseData['bday'] == '0000-00-00' || $baseData['bday'] == '0100-01-01') {
            $baseScore -= 1;
        }
        //默认值  没有选 是否 为2 
        if ($family_like_has == 0) {
            $baseScore += 1;
        } else if ($family_like_has == 2) {
            $baseScore -= 1;
        }
        if ($sex == 0) {
            $baseScore += 1;
        } else if ($sex == 2) {
            $baseScore -= 1;
        }
        if ($has_chuiti == 0) {
            $baseScore += 1;
        } else if ($has_chuiti == 2) {
            $baseScore -= 1;
        }

        //type
        $type = convertsArray(DB::select("select * from z_pituitary_user_type where user_id = $userId limit 1"));

        if (!empty($type)) {
            $baseScore += 1;
        }
        // 实际得分
        $actualScore = $baseScore * 100;
        $allScore = 1000;
        // 删除旧的完成度
        DB::delete("
                delete from z_pituitary_complete where user_id = $userId and visit_level = $visitLevel
        ");
        $time = Carbon::now()->toDateTimeString();
        ZPituitaryComplete::insertOnDuplicateKey([
            'visit_level' => $visitLevel,
            'user_id' => $userId,
            'terminal_flg' => 0,
            'template_id' => '00',
            'category_id' => 0,
            'complete_a' => $allScore,
            'complete_s' => $actualScore,
            'complete_b' => round($actualScore / $allScore * 100, 2),
            'create_at' => $time,
            'update_at' => $time
        ]);
        return true;
    }

    public function answerScore($userId, $visitLevel) {
        $answers = $this->getAnswerListScore($userId, $visitLevel);
        // 洗出所有的 option_id ,用来做题目过滤
        $optionIds = collect($answers)->pluck('option_id')->toArray();
        // 以 问题id 做 key ，方便处理
        $ques = collect($answers)->groupBy('question_id')->toArray();

        //当出现某个值时 这个答案才有意义
        $belongRole = [
            12612 => [127],
            11901 => [120],
            12101 => [122],
            12301 => [124],
            12501 => [126],
            14101 => [142],
            14401 => [145],
            20601 => [153],
            15302 => [154, 155, 156],
            15303 => [157],
            // v1.1
            13801 => [209],
            13901 => [210],
            14001 => [211],
            21201 => [213],
            21401 => [215,216,217],
            21801 => [219,220],
            22301 => [224,225,226],
        ];
        foreach ($belongRole as $k => $v) {
            if (!in_array($k, $optionIds)) {
                foreach ($v as $id) {
                    unset($ques[$id]);
                }
            }
        }
        //当题目碰到以下答案 则无效
        $clearRole = [
            127 => [12601, 12602, 12603, 12604, 12605, 12607, 12608, 12609, 12610, 12611],
            154 => [15301, 15303, 15304],
            155 => [15301, 15303, 15304],
            156 => [15301, 15303, 15304],
            157 => [15301, 15302, 15304],
        ];


        //出现以上option的话，直接把对应的题目删掉
        foreach ($clearRole as $k => $v) {
            if (array_intersect($v, $optionIds)) {
                unset($ques[$k]);
            }
        }

        // 该访视 每个 章节满分分数
        $fullScore = $this->getFullMarkScore($visitLevel);
        $fullScore = collect($fullScore)->groupBy('template_id')->toArray();
        $templateIds = array_keys($fullScore);


        $insertData = [];
        foreach ($fullScore as $item) {
            $insertData[$item[0]['template_id']]['category_id'] = $item[0]['category_id'];
            $insertData[$item[0]['template_id']]['question_score'] = $item[0]['question_score'];
            $insertData[$item[0]['template_id']]['answer_score'] = 0;
        }
        // 数据集合变量，方便后面统计
        $converge = [];
        // 计算每一道题目的得分 
        foreach ($ques as $k => $v) {
            if (in_array($v[0]['template_id'], $templateIds) && $v[0]['answer_name']) {
                if ($v[0]['option_type'] == 1) {
                    $score = collect($v)->max('answer_score');
                    $converge[$k] = $score;
                } else {
                    $score = collect($v)->pluck('answer_score')->sum();
                    $converge[$k] = $score;
                }
                $insertData[$v[0]['template_id']]['answer_score'] += $score;
            }
        }


        //垂体用药
        if (in_array(13601, $optionIds)) {
            if ($this->getCuiTiDrugs($userId)) {
                $insertData[13]['answer_score'] += 50;
            }
        }

        //非垂体用药
        if (in_array(15201, $optionIds)) {
            if ($this->getNoCuiTiDrugs($userId)) {
                $insertData[15]['answer_score'] += 50;
            }
        }

        if (!empty($insertData)) {
            $templateData = [];
            foreach ($insertData as $k => $v) {
                $templateData[] = [
                    'visit_level' => $visitLevel,
                    'user_id' => $userId,
                    'terminal_flg' => 0,
                    'template_id' => $k,
                    'category_id' => $v['category_id'],
                    'complete_a' => $v['question_score'],
                    'complete_s' => $v['answer_score'],
                    'complete_b' => $v['question_score'] ? round($v['answer_score'] / $v['question_score'] * 100, 2) : 0,
                    'create_at' => date("Y-m-d H:i:s"),
                    'update_at' => date("Y-m-d H:i:s")
                ];
            }

            ZPituitaryComplete::insertOnDuplicateKey($templateData);
        }

        //计算一个 总完成度
        $allPercent = DBSelect("select * from z_pituitary_complete where user_id =$userId and visit_level = $visitLevel");
        $allSum = collect($allPercent)->pluck('complete_a')->sum();
        $allScore = collect($allPercent)->pluck('complete_s')->sum();

        //sentry 收集到$allSum有为0的情况，除0报错
        if ($allSum == 0) {
            $complete_b = 0;
        } else {
            $complete_b = round($allScore / $allSum * 100, 2);
        }
        $others = [];
        $others[] = [
            'visit_level' => $visitLevel,
            'user_id' => $userId,
            'terminal_flg' => 0,
            'template_id' => 0,
            'category_id' => 100,
            'complete_a' => $allSum,
            'complete_s' => $allScore,
            'complete_b' => $complete_b,
            'create_at' => date("Y-m-d H:i:s"),
            'update_at' => date("Y-m-d H:i:s")
        ];

        ZPituitaryComplete::insertOnDuplicateKey($others);

        return true;
    }

    /**
     * @param $userId
     * @param $visitLevel
     * @return array
     * 获取答案数据,以及用户回答分数
     */
    private function getAnswerListScore($userId, $visitLevel) {
        $answers = DBSelect("
         
 SELECT
            a.template_id,
            a.question_id,
            a.subquestion_id,
            a.answer_id,
            a.answer_name,
            b.option_type,
            b.option_id,
            b.complete_score,
            b.question_score,
            b.answer_score,
            b.question_level,
            c.score_weight 
        FROM
            ( SELECT * FROM z_pituitary_answer WHERE user_id = $userId AND visit_level = $visitLevel and answer_name !='' ) a
            INNER JOIN z_pituitary_question b ON a.answer_id = b.option_id  and a.question_id = b.question_id 
            INNER JOIN ( SELECT * FROM z_pituitary_control WHERE visit_level = $visitLevel ) c ON b.question_id = c.question_id 
        WHERE
            b.complete_score > 0 
            AND b.complete_flg = 1 
            AND c.complete_flg_v = 1 
             
        ORDER BY
            a.question_id,
            a.subquestion_id,
            a.answer_id
        ");
        return $answers;
    }

    /**
     * @param $visitLevel
     * @param $sex
     * @return array
     * 获取章节满分数据
     */
    private function getFullMarkScore($visitLevel = 1) {
        $fullScore = DBSelect(" 
            select a.category_id, ff.* from (select template_id,sum(question_score) as question_score from (
select B.template_id, B.question_score from z_pituitary_control  A
            INNER JOIN z_pituitary_question B on A.template_id = B.template_id AND A.chapter_id = B.chapter_id 
             AND A.question_id = B.question_id 
              where B.complete_flg = 1 and B.question_level = 1 and A.visit_level = $visitLevel
            group by B.template_id,B.question_id ) ff GROUP BY template_id) ff
left join z_pituitary_qss_template a on ff.template_id = a.id 
         ");
        return $fullScore;
    }

    /**
     * 获取垂体用药
     */
    public function getCuiTiDrugs($userId) {
        $drugs = DBSelectOne("
select a.id from z_pituitary_manage_drugs a
left join z_pituitary_drug b on a.drug_id = b.id
left join z_pituitary_drug_type  c on b.type_id = c.id
where user_id = $userId  and c.type_category = 1 
and a.is_deleted = 0 limit 1 ");
        return $drugs;
    }

    public function getNoCuiTiDrugs($userId) {
        $drugs = DBSelectOne("
select a.id from z_pituitary_manage_drugs a
left join z_pituitary_drug b on a.drug_id = b.id
left join z_pituitary_drug_type  c on b.type_id = c.id
where user_id = $userId  and c.type_category != 1 
and a.is_deleted = 0 limit 1 ");
        return $drugs;
    }

}
